package org.ghost.springboot.demo.util;


import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.stream.Stream;

/**
 * Created by yarnliu on 2017-01-10.
 */
public class HttpRequestUtil {
    public static String getIpAddr(HttpServletRequest request) {
        //step 1先从X-Forwarded-For取值
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP。
            String realIp = Stream.of(ip.split(",")).filter(StringUtils::isNotBlank).findFirst().orElse(null);
            if (StringUtils.isNotBlank(realIp)) {
                return realIp;
            }
        }

        //step 2再从X-Real-IP取值
        ip = request.getHeader("X-Real-IP");
        if (StringUtils.isNotBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        } else {
            return request.getRemoteAddr();
        }
    }
}
